define([
    'require',
    'angular',
    'underscore'
], function (require, angular, _) {
    return function ($scope, $routeParams, $http, RuleSerivce, GillionMsg,$dataSourceManager,Resource,$compile,$timeout) {
        var  unitCaseResource,unitCaseMocks,unitCaseAsset,unitCaseResults,childUnitCaseParams,unitCaseParams;
        RuleSerivce.promises().then(function () {
            $scope.groupId = $scope.currPackage.groupId;
            $scope.artifactId = $scope.currPackage.artifactId;
            $scope.packageId=$scope.currPackage.id;
            var param = {};
            param.groupId=$scope.groupId;
            param.artifactId=$scope.artifactId;
            $scope.records=[];//展开子节点时使用
            $timeout(function(){
                $dataSourceManager.dataSources["unitCaseList"].params = param;
                $dataSourceManager.dataSources["unitCaseList"].doRequestData();
            },500);

            unitCaseResource = Resource("/grule-manager/unitcases/:id", {
                id: "@id"
            });
            unitCaseMocks = Resource("/grule-manager/unitcases/mocks/:id", {
                id: "@id"
            });
            unitCaseAsset = Resource("/grule-manager/unitcases/assets/:id", {
                id: "@id"
            });

            unitCaseResults = Resource("/grule-manager/unitcases/results/:id", {
                id: "@id"
            });
            unitCaseParams = Resource("/grule-manager/unitcases/params/:id", {
                id: "@id"
            });

            childUnitCaseParams = Resource("/grule-manager/unitcases/params/child/:id", {
                id: "@id"
            });
        });


        $scope.$on("unitCaseList", function (context, dataSource) {
            $scope.unitcases =dataSource.records;
            //默认选中首个
            $timeout(function () {
                if ($scope.unitcases.length > 0) {
                    $scope.viewCase($scope.unitcases[0].id, $scope.unitcases[0].unitCaseName);
                }
            },200);
        });

        $scope.addTest=function(){
            $scope.dlg = GillionMsg.showUrl({
                title: '新建用例',
                url: '/html2/unitcases/unitCaseManager',
                data:{artifactId:$scope.artifactId,groupId:$scope.groupId},
                height:200,
                width:400,
                onClose: function(){
                    var param={};
                    param.groupId=$scope.groupId;
                    param.artifactId=$scope.artifactId;
                    $dataSourceManager.dataSources["unitCaseList"].params = param;
                    $dataSourceManager.dataSources["unitCaseList"].doRequestData();
                }
            });
        }

        $scope.editCase=function(id){
            $scope.dlg=GillionMsg.showUrl({
                title:'编辑用例',
                url:'/html2/unitcases/editCaseManager',
                height:200,
                width:400,
                data:{
                    "id":id
                },
                onClose:function(){
                    $dataSourceManager.dataSources["unitCaseList"].doRequestData();
                }
            })
        }

        function refresh(){
            Resource("/grule-manager/unitcases/newParams/:id", {id: '@id'}).get({
                id:  $scope.unitCaseId
            }, function (response) {
                $scope.unitCaseParams =response.data;
            });
        }

        $scope.addParam = function () {
            var unitCaseParam={};
            unitCaseParam.unitCaseId=$scope.unitCaseId;
            unitCaseParam.packageId=$scope.packageId;
            if($scope.unitCaseId==null){
                GillionMsg.alert('提示', '请选择测试用例！');
                return ;
            }
            $scope.dlg = GillionMsg.showUrl({
                title: '新增参数',
                url: '/html2/unitcases/paramManager',
                data:unitCaseParam,
                height:300,
                width:200,
                onClose: function(){
                    refresh();
                }
            });
        };
        $scope.editParam = function (uParam) {
            var unitCaseParam={};
            unitCaseParam.id=uParam.id;
            unitCaseParam.unitCaseId=$scope.unitCaseId;
            unitCaseParam.dataType=uParam.dataType;
            unitCaseParam.paramName=uParam.paramName;
            unitCaseParam.param=uParam.param;
            unitCaseParam.packageId=$scope.packageId;
            if(unitCaseParam.dataType!="List"){
                $scope.dlg = GillionMsg.showUrl({
                    title: '修改参数',
                    url: '/html2/unitcases/paramManager',
                    data:{
                        "unitCaseParam":unitCaseParam,
                        "status":$scope.currPackage.status
                    },
                    height:300,
                    width:200,
                    onClose: function(){
                        refresh();
                    }
                });
            }else{
                $scope.dlg = GillionMsg.showUrl({
                    title: '修改费率',
                    url: '/html2/unitcases/listManager',
                    data:{
                        "unitCaseParam":unitCaseParam,
                        "status":$scope.currPackage.status
                    },
                    height:350,
                    width:200,
                    onClose: function(){
                        refresh();
                    }
                });
            }

        };


        $scope.addList = function () {
            var unitCaseParam={};
            unitCaseParam.unitCaseId=$scope.unitCaseId;
            unitCaseParam.packageId=$scope.packageId;
            unitCaseParam.dataType="List";
            if($scope.unitCaseId==null){
                GillionMsg.alert('提示', '请选择测试用例！');
                return ;
            }
            $scope.dlg = GillionMsg.showUrl({
                title: '新增数组',
                url: '/html2/unitcases/listManager',
                data:unitCaseParam,
                height:350,
                width:200,
                onClose: function(){
                    refresh();
                }
            });
        };

        $scope.addChild = function (id,type) {
            var unitCaseParam={};
            //unitCaseParam.id=id;
            unitCaseParam.unitCaseId=$scope.unitCaseId;
            unitCaseParam.packageId=$scope.packageId;
            unitCaseParam.parentId=id;
            if(type=='map'||type==2){
                $scope.dlg = GillionMsg.showUrl({
                    title: '新增子参数',
                    url: '/html2/unitcases/paramManager',
                    data:unitCaseParam,
                    height:300,
                    width:200,
                    onClose: function(){
                        refresh()
                    }
                });
            }else if(type=='list'||type==1){
                $scope.dlg = GillionMsg.showUrl({
                    title: '新增数组',
                    url: '/html2/unitcases/listManager',
                    data:unitCaseParam,
                    height:350,
                    width:200,
                    onClose: function(){
                        refresh();
                    }
                });
            }

        };


        $scope.deleteParam = function (id) {
            GillionMsg.confirm('提示', '是否确定删除！', function(flag){
                if (flag) {
                    unitCaseParams.delete({
                        id: id
                    }, function (response) {
                        if(response.success){
                            refresh();
                        }
                    })
                }
            })
        };


        $scope.deleteCase = function (id) {
            GillionMsg.confirm('提示', '是否删除用例！', function(flag){
                if (flag) {
                    unitCaseResource.delete({
                        id: id
                    }, function (response) {
                        if (response.success) {
                            GillionMsg.alert('提示', '删除成功！', function(){
                                $dataSourceManager.dataSources["unitCaseList"].doRequestData();
                            });
                        }
                    });
                }
            });
        };

        $scope.viewCase = function (id,name) {
            $scope.unitCaseName = name;
            var list = document.getElementsByName("caseList");
            for(var i=0; i< list.length; i++){
                list[i].className = "engine-test-case";
            }
            document.getElementById(id).setAttribute("class","engine-test-case  engine-test-case-on");
            $scope.unitCaseId=id;
            var param = {};
            param.unitCaseId=id;
            $dataSourceManager.dataSources["UnitCaseMockSource"].params = param;
            $dataSourceManager.dataSources["UnitCaseMockSource"].doRequestData();
            $dataSourceManager.dataSources["AssetSource"].params = param;
            $dataSourceManager.dataSources["AssetSource"].doRequestData();
            $dataSourceManager.dataSources["ResultsSource"].params = param;
            $dataSourceManager.dataSources["ResultsSource"].doRequestData();
            refresh();

        };
        $scope.addMock = function () {
            if($scope.unitCaseId==null){
                GillionMsg.alert('提示', '请选择测试用例！');
                return ;
            }
            $scope.dlg = GillionMsg.showUrl({
                title: '新增Mock',
                url: '/html2/unitcases/mockManager',
                data:{unitCaseId:$scope.unitCaseId},
                height:250,
                width:200,
                onClose: function(data){
                    $dataSourceManager.dataSources["UnitCaseMockSource"].doRequestData();
                }
            });
        };
        $scope.updateMock = function (row) {
            console.log(row);
            $scope.dlg = GillionMsg.showUrl({
                title: '修改Mock',
                url: '/html2/unitcases/mockManager',
                data:row,
                height:300,
                width:200,
                onClose: function(){
                    $dataSourceManager.dataSources["UnitCaseMockSource"].doRequestData();
                }
            });
        };
        $scope.removeMock=function(row){
            unitCaseMocks.delete({
                id: row.id
            }, function (response) {
                if (response.success) {
                    GillionMsg.alert('提示', '删除成功！');
                    $dataSourceManager.dataSources["UnitCaseMockSource"].doRequestData();
                }
            });
        };

        $scope.removeAsset=function(row){
            unitCaseAsset.delete({
                id: row.id
            }, function (response) {
                if (response.success) {
                    GillionMsg.alert('提示', '删除成功！');
                    $dataSourceManager.dataSources["AssetSource"].doRequestData();
                }
            });
        };
        $scope.addAsset = function () {
            if($scope.unitCaseId==null){
                GillionMsg.alert('提示', '请选择测试用例！');
                return ;
            }
            $scope.dlg = GillionMsg.showUrl({
                title: '新增断言',
                url: '/html2/unitcases/assetManager',
                data:{unitCaseId:$scope.unitCaseId},
                height:200,
                width:200,
                onClose: function(data){
                    $dataSourceManager.dataSources["AssetSource"].doRequestData();
                }
            });
        };
        $scope.updateAsset= function (row) {
            $scope.dlg = GillionMsg.showUrl({
                title: '修改断言',
                url: '/html2/unitcases/assetManager',
                data:row,
                height:300,
                width:200,
                onClose: function(){
                    $dataSourceManager.dataSources["AssetSource"].doRequestData();
                }
            });
        };
        $scope.removeResults=function(row){
            unitCaseResults.delete({
                id: row.id
            }, function (response) {
                if (response.success) {
                    GillionMsg.alert('提示', '删除成功！');
                    $dataSourceManager.dataSources["ResultsSource"].doRequestData();
                }
            });
        };


        $scope.addResults = function () {
            if($scope.unitCaseId==null){
                GillionMsg.alert('提示', '请选择测试用例！');
                return ;
            }
            $scope.dlg = GillionMsg.showUrl({
                title: '新增结果集期望',
                url: '/html2/unitcases/resultsManager',
                data:{unitCaseId:$scope.unitCaseId},
                height:300,
                width:200,
                onClose: function(){
                    $dataSourceManager.dataSources["ResultsSource"].doRequestData();
                }
            });
        };
        $scope.updateResults= function (row) {
            $scope.dlg = GillionMsg.showUrl({
                title: '修改结果集期望',
                url: '/html2/unitcases/resultsManager',
                data:row,
                height:300,
                width:200,
                onClose: function(){
                    $dataSourceManager.dataSources["ResultsSource"].doRequestData();
                }
            });
        };

        $scope.importParams=function (){
            var fd =new FormData();
            var file = document.getElementById('paramsFile').files[0];
            if($scope.unitCaseId==undefined){
                GillionMsg.alert('提示', '请创建测试用例！');
                return;
            }
            if(file==undefined){
                GillionMsg.alert('提示', '请选择文件！');
                return;
            }
            fd.append('file', file);
            fd.append('unitCaseId', $scope.unitCaseId);
            $http({
                method:'POST',
                url:"/grule-manager/unitcases/importParams",
                data: fd,
                headers: {'Content-Type':undefined},
                transformRequest: angular.identity
            }).success( function ( response ) {
                if(response.success){
                    GillionMsg.alert('提示', '导入成功！');
                    refresh();
                    $scope.detailsShow = true;
                }
            });
        };

        $scope.importParams2=function (){
            var fd =new FormData();
            var file = document.getElementById('objectFile').files[0];
            if($scope.unitCaseId==undefined){
                GillionMsg.alert('提示', '请创建测试用例！');
                return;
            }
            if(file==undefined){
                GillionMsg.alert('提示', '请选择文件！');
                return;
            }
            fd.append('file', file);
            fd.append('unitCaseId', $scope.unitCaseId);
            $http({
                method:'POST',
                url:"/grule-manager/unitcases/importParams2",
                data: fd,
                headers: {'Content-Type':undefined},
                transformRequest: angular.identity
            }).success( function ( response ) {
                if(response.success){
                    GillionMsg.alert('提示', '导入成功！');
                    refresh();
                    $scope.detailsShow = true;
                }
            });
        };

        window.showFileName=function(name){

            var fd =new FormData();
            var file = document.getElementById('objectFile').files[0];
            if($scope.unitCaseId==undefined){
                GillionMsg.alert('提示', '请创建测试用例！');
                return;
            }
            if(file==undefined){
                GillionMsg.alert('提示', '请选择文件！');
                return;
            }

            GillionMsg.confirm('提示', '是否确定上传文件'+file.name+'！', function(flag){
                if (flag) {
                    fd.append('file', file);
                    fd.append('unitCaseId', $scope.unitCaseId);
                    $http({
                        method:'POST',
                        url:"/grule-manager/unitcases/importParams2",
                        data: fd,
                        headers: {'Content-Type':undefined},
                        transformRequest: angular.identity
                    }).success( function ( response ) {
                        if(response.success){
                            GillionMsg.alert('提示', '导入成功！');
                            refresh();
                            $scope.detailsShow = true;
                        }
                    });
                }
            });
        };

        $scope.exportParams=function(){
            location.href="/grule-manager/unitcases/paramsToJson?unitCaseId="+ $scope.unitCaseId;

        }

        $scope.viewObject=function (id,margin){
            var type1 = 1;
            var type2 =2
            if($("#"+id).text()=="对象[-]"){
                var elements = $("[name="+id+"]");
                elements.remove();
                $("#"+id).text("对象[+]");
                return;
            }
            $("#"+id).text("对象[-]");
            childUnitCaseParams.get({
                id: id
            }, function (response) {
                if (response.success) {
                    $scope.records.push(response.data);
                    var size = $scope.records.length-1;
                    angular.element("#son" + id).after(
                        $compile(
                            "<tr ng-repeat='item in records["+size+"]' id='son{{item.id}}' name='{{item.parentId}}'>"+
                            "<td ng-if=\"item.dataType!='Object'\">"+
                            "<div class='model-value model-value-son model-value-border'pg-sta='{{status}}|0'  style='margin-left:" + 20 * margin + "px'>" +
                            "<div class='model-value-l'><button type='button'  id='{{item.id}}'  class='engine-btn-model' ng-dblclick='editParam(item)'>{{item.dataType}}</button></div>" +
                            "<div class='model-value-r'>{{item.paramName}}</div>" +
                            "<div class='model-value-right'>" +
                            "<span class='results'>{{item.param| maxLength:20}}</span>" +
                            "<span class='remove'><a href='javascript:void(0)'pg-per='{{packageId}}|1' pg-sta='{{status}}|0' ng-click='deleteParam(item.id)'&apos;><i class='icon-engine-removeove'></i></a></span>" +
                            "</div>" +
                            "<div class='clear'></div>" +
                            "</div>" +
                            "</td>" +
                            "<td ng-if=\"item.dataType=='Object'\" >" +
                            "<div class='model-value model-value-son model-value-border' style='margin-left:"+20*margin+"px'>"+
                            "<div class='model-value-l'><button type='button' id='{{item.id}}'   class='engine-btn-model' ng-click='viewObject(item.id," + (margin + 1) + ")' ng-dblclick='editParam(item)'>对象[+]</button></div>" +
                            "<div class='model-value-r'>{{item.paramName}}</div>" +
                            "<div class='model-value-right'>" +
                            "<span class='results'><a href='javascript:void(0)'  pg-per='{{packageId}}|1' ng-click='addChild(item.id,"+type1+")'><i class='icon-engine-plus'>L</i></a><a href='javascript:void(0)'  pg-per='{{packageId}}|1' ng-click='addChild(item.id,"+type2+")'><i class='icon-engine-plus'>M</i></a>{{item.param}}</span>" +
                            "<span class='remove'><a href='javascript:void(0)' pg-per='{{packageId}}|1' ng-click='deleteParam(item.id)'><i class='icon-engine-removeove'></i></a></span>" +
                            "</div>" +
                            "<div class='clear'></div>" +
                            "</div>" +
                            "</td>"+
                            "</tr>"

                        )
                        ($scope)
                    )
                }
            })
        }

    };
});